/*
 * @Author: lichao 1246877006@qq.com
 * @Date: 2024-09-26 15:27:17
 * @LastEditors: lichao 1246877006@qq.com
 * @LastEditTime: 2024-09-26 16:44:57
 * @FilePath: \algorithm\hello-algo\6 哈希表\6.1哈希表.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
// 键值对类
class Pair {
    constructor(key, val) {
        this.key = key
        this.val = val
    }
}

// 基于数组实现哈希表
class ArrayHasMap {
    #buckest;
    constructor() {
        this.#buckest = new Array(100).fill(null)
    }

    // 生产哈希值
    createHasKey(key) {
        return key % 100
    }
    
    // 添加键值对
    set(key, val) {
        let index = this.createHasKey(key)
        this.#buckest[index] = new Pair(key, val)
    }

    // 获取值
    get(key) {
        const index = this.createHasKey(key)
        let pair = this.#buckest[index]
        if(pair === null) return pair
        return pair.val
    }

    // 删除操作
    delete(key) {
        const index = this.createHasKey(key)
        this.#buckest[index] = null
    }

    // 获取所有的键值对
    entries() {
        let arr = []
        for(let i = 0; i < this.#buckest.length; i++) {
            const pair = this.#buckest[i]
            if(pair) {
                arr.push(pair)
            }
        }
        return arr
    }

    // 获取所有的键
    keys() {
        let arr = []
        for(let i = 0; i < this.#buckest.length; i++) {
            const pair = this.#buckest[i]
            if(pair) {
                arr.push(pair.key)
            }
        }
        return arr
    }

    // 获取所有的之
    values() {
        let arr = []
        for(let i = 0; i < this.#buckest.length; i++) {
            const pair = this.#buckest[i]
            if(pair) {
                arr.push(pair.val)
            }
        }
        return arr
    }

    print() {
        let pairSet = this.entries()
        for (const { key, value } of pairSet) {
            console.info(`${key} -> ${value}`)
        }
    }

}